package v1

import (
	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
	"myginblog/model"
	"myginblog/utils/errmsg"
	"myginblog/utils/httpresponse"
	"net/http"
	"strconv"
)

// AddCategory 添加分类
func AddCategory(c *gin.Context) {
	var data model.Category
	err := c.ShouldBindJSON(&data)
	if err != nil {
		log.Error(err)
		r = httpresponse.SetResponseBody(http.StatusBadRequest, err.Error(), "")
		c.JSON(http.StatusOK, r)
		return
	}
	code := model.CheckCategory(data.Name)
	if code != errmsg.SUCCESS {
		r = httpresponse.SetResponseBody(code, "", data)
		c.JSON(http.StatusOK, r)
		return
	}
	code = model.CreatCategory(&data)
	if code != errmsg.SUCCESS {
		r = httpresponse.SetResponseBody(code, "", data)
		c.JSON(http.StatusOK, r)
		return
	}
	r = httpresponse.SetResponseBody(code, "", data)
	c.JSON(http.StatusOK, r)
}

//	todo 查询分类下的所有文章

// GetCategory 查询分类列表
func GetCategory(c *gin.Context) {
	pageSize, err := strconv.Atoi(c.Query("pagesize"))
	if err != nil {
		log.Infoln(err)
	}
	pageNum, err := strconv.Atoi(c.Query("pagenum"))
	if err != nil {
		log.Infoln(err)
	}
	data := model.GetCategory(pageSize, pageNum)
	r = httpresponse.SetResponseBody(errmsg.SUCCESS, "", data)
	c.JSON(http.StatusOK, r)
}

// EditCategory 编辑分类名
func EditCategory(c *gin.Context) {
	var data model.Category
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		log.Infoln(err)
	}
	err = c.ShouldBindJSON(&data)
	if err != nil {
		log.Error(err)
		r = httpresponse.SetResponseBody(http.StatusBadRequest, err.Error(), "")
		c.JSON(http.StatusOK, r)
		return
	}
	code := model.CheckCategory(data.Name)
	if code != errmsg.SUCCESS {
		r = httpresponse.SetResponseBody(code, "", "")
		c.JSON(http.StatusOK, r)
		c.Abort()
		return
	}
	code = model.EditCategory(id, &data)
	if code != errmsg.SUCCESS {
		r = httpresponse.SetResponseBody(code, "", data)
		c.JSON(http.StatusOK, r)
		c.Abort()
		return
	}
	r = httpresponse.SetResponseBody(errmsg.SUCCESS, "", data)
	c.JSON(http.StatusOK, r)
}

// DeleteCategory 删除分类
func DeleteCategory(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		log.Infoln(err)
	}
	code := model.DeleteCategory(id)
	if code != errmsg.SUCCESS {
		r = httpresponse.SetResponseBody(code, "", nil)
		c.JSON(http.StatusOK, r)
		return
	}
	r = httpresponse.SetResponseBody(code, "", nil)
	c.JSON(http.StatusOK, r)
}
